<%@ page language="java" contentType="text/html; charset=UTF-8"
	import="java.util.*,com.cap.bts.crmdp.dealer.coupon.domain.Ticket"
	pageEncoding="UTF-8"%>

<%
    Ticket ticket = (Ticket) request.getAttribute("ticket");
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>优惠券修改</title>
<%@include file="../include/include.jsp"%>
<link rel="stylesheet" type="text/css" href="${csspath }/public.css" />
<script type="text/javascript" src="${jspath}/jquery/jquery-2.1.3.js"></script>
<link rel="stylesheet" type="text/css"
	href="${bootstrapPath}/css/bootstrap.css" />
<script type="text/javascript" src="${bootstrapPath}/js/bootstrap.js"></script>
<script type="text/javascript"
	src="${bootstrapPath}/js/bootstrap3-validation.js"></script>

<script type="text/javascript" src="${layerPath}/layer.js"></script>
</head>

<style>
.hr {
	text-align: center;
	width: 100%;
	background-color: #0071C1;
	height: 1px;
	margin-bottom: 10px;
}

.rowDiv {
	width: 90%;
}

.formDiv {
	float: left;
	width: 50%;
}

.textarea {
	width: 700px;
	height: 100px;
	max-width: 700px;
	max-height: 100px;
	resize: none;
}

.btnLength {
	width: 70px;
}
</style>

<script type="text/javascript">
	$(function() {

		$("#couponForm").validation({
			icon : true
		});
		//返回
		$("#returnBtn")
				.click(
						function() {
							$("#couponForm")
									.attr('action',
											'${webcontext}/crmdp/dealer/coupon/toDefineTicKet');
							$("#couponForm").submit();
						});

		//修改保存
		$("#saveBtn")
				.click(
						function() {
							if ($("#couponForm").valid(this, '内容出错') == false) {
								return false;
							}
							var radio = document.getElementsByName("smsRemind");
							var smsRemind = null;
							for ( var i = 0; i < radio.length; i++) {
								if (radio[i].checked == true) {
									smsRemind = radio[i].value;
									break;
								}
							}
							$
									.ajax({
										url : '${webcontext}/crmdp/dealer/coupon/updateTicketInfo',
										type : 'post',
										data : {
											'id' : $("#ticketDefId").val(),
											'ticketType' : $("#ticketType")
													.val(),
											'ticketName' : $("#ticketName")
													.val(),
											'maximunTimes' : $("#maximunTimes")
													.val(),
											'deductionMethod' : $(
													"#deductionMethod").val(),
											'deductionAmount' : $(
													"#deductionAmount").val(),
											'verificationMethod' : $(
													"#verificationMethod")
													.val(),
											'smsRemind' : smsRemind
										},
										success : function(data) {
											if (data.code == true) {
												jAlert(
														data.msg,
														"提示",
														function() {
															$("#couponForm")
																	.attr(
																			'action',
																			'${webcontext}/crmdp/dealer/coupon/toEditTicket');
															$("#couponForm")
																	.submit();
														});
											} else if (data.code == false) {
												jAlert(data.msg, "提示",function(){
													$("#couponForm")
													.attr(
															'action',
															'${webcontext}/crmdp/dealer/coupon/toEditTicket');
													$("#couponForm")
															.submit();
												});
											}
										},
										error : function() {
											jAlert("服务器错误，请联系管理员", "提示");
										},
									});
						});

	});
	
	//适用范围
	function toScopeOfTicket(o){
		$.ajax({
			url : '${webcontext}/crmdp/dealer/coupon/checkPackageByTicketDefId',
			type : 'post',
			data : {
				'ticketDefId' : $("#ticketDefId").val()
			},
			success : function(data) {
				if (data.code == true) {
					var  url = "${webcontext}/crmdp/dealer/coupon/toScopeOfTicket?ticketLineId=";
					layer.open({
					    type: 2,
					    title: '适用范围',
					    shadeClose: false,
					    closeBtn: false,
					    shade: 0.1, 
					    offset : ['12%' , '15%'],
					    area: ['800px', '500px'],
					    content: url + o,//iframe的url
					}); 
				} else if (data.code == false) {
					jAlert(data.msg, "提示");
				}
			},
			error : function() {
				jAlert("服务器错误，请联系管理员", "提示");
			},
		});
	}

	window.onload = function() {
		var deductionMethod = '${ticket.deductionMethod}';
		if (deductionMethod != null & deductionMethod != "") {
			$("#deductionMethod").val(deductionMethod);
		}
		var verificationMethod = '${ticket.verificationMethod}';
		if (verificationMethod != null & verificationMethod != "") {
			$("#verificationMethod").val(verificationMethod);
		}
		var smsRemind = '${ticket.smsRemind}';
		if (smsRemind != null & smsRemind != "") {
			if (smsRemind == 1) {
				$("input[name='smsRemind'][value=1]").attr("checked", true);
			} else if (smsRemind == 0) {
				$("input[name='smsRemind'][value=0]").attr("checked", true);
			}
		}
	};

	//删除优惠券的详细信息
	function removeCouponLine(id) {
		$.ajax({
			url : '${webcontext}/crmdp/dealer/coupon/checkPackageByTicketDefId',
			type : 'post',
			data : {
				'ticketDefId' : $("#ticketDefId").val()
			},
			success : function(data) {
				if (data.code == true) {
					//询问框
					jConfirm(
							"确定要删除数据吗？",
							"确认",
							function(r) {
								if (r) {
									$
											.ajax({
												url : '${webcontext}/crmdp/dealer/coupon/removeTiketLineInfo',
												type : 'post',
												data : {
													'id' : id,
													'ticketDefId' : $("#ticketDefId").val()
												},
												success : function(data) {
													if (data.code == true) {
														jAlert(
																data.msg,
																"提示",
																function() {
																	$("#couponForm")
																			.attr('action',
																					'${webcontext}/crmdp/dealer/coupon/toEditTicket');
																	$("#couponForm")
																			.submit();
																});
													} else if (data.code == false) {
														jAlert(data.msg, "提示");
													}
												},
												error : function() {
													jAlert("服务器错误，请联系管理员", "提示");
												},
											});
								}
							});
				} else if (data.code == false) {
					jAlert(data.msg, "提示");
				}
			},
			error : function() {
				jAlert("服务器错误，请联系管理员", "提示");
			},
		});
	}

	//修改优惠券的详细信息
	function editCouponLineInfo(id) {
		$.ajax({
			url : '${webcontext}/crmdp/dealer/coupon/checkPackageByTicketDefId',
			type : 'post',
			data : {
				'ticketDefId' : $("#ticketDefId").val()
			},
			success : function(data) {
				if (data.code == true) {
					var qticketType = $("#qticketType").val();
					var qticketName = $("#qticketName").val();
					var pager = $("#pager").val();
					layer.open({
						type : 2,
						title : '产品修改',
						shadeClose : false,
						closeBtn : false,
						shade : 0.1,
						offset : [ '16%', '28%' ],
						area : [ '540px', '200px' ],
						content : '${webcontext}/crmdp/dealer/coupon/toCouponLinePage?id='
								+ id + "&qticketType=" + qticketType + "&qticketName="
								+ qticketName + "&pager.currentPage=" + pager
					});
				} else if (data.code == false) {
					jAlert(data.msg, "提示");
				}
			},
			error : function() {
				jAlert("服务器错误，请联系管理员", "提示");
			},
		});
	}

	//新增产品
	function insertRow() {
		$.ajax({
			url : '${webcontext}/crmdp/dealer/coupon/checkPackageByTicketDefId',
			type : 'post',
			data : {
				'ticketDefId' : $("#ticketDefId").val()
			},
			success : function(data) {
				if (data.code == true) {
					var ticketDefId = $("#ticketDefId").val();
					var qticketType = $("#qticketType").val();
					var qticketName = $("#qticketName").val();
					var pager = $("#pager").val();
					layer
							.open({
								type : 2,
								title : '项目新增',
								shadeClose : false,
								closeBtn : false,
								shade : 0.1,
								offset : [ '16%', '28%' ],
								area : [ '500px', '200px' ],
								content : '${webcontext}/crmdp/dealer/coupon/saveCouponLineDetails?ticketDefId='
										+ ticketDefId
										+ "&qticketType="
										+ qticketType
										+ "&qticketName="
										+ qticketName
										+ "&pager.currentPage=" + pager
							});
				} else if (data.code == false) {
					jAlert(data.msg, "提示");
				}
			},
			error : function() {
				jAlert("服务器错误，请联系管理员", "提示");
			},
		});
	}
	
	function editEligibility(id){
		
		
	}
	
	
	function removeEligibility(id){
		layer.confirm('数据删除后将不可恢复，确认删除？', {
			offset: ['150px', '350px'],
		    btn: ['确认','取消'] //按钮
		}, function(){
			$.ajax({
				url : '${webcontext}/crmdp/dealer/coupon/eligibility/del/' + id,
				type : 'post',
				data : {
					'ticketDefId' : $("#ticketDefId").val()
				},
				success : function(data) {
					if (data.success == true) {
						window.location.reload();
					} else{
						layer.msg('操作失败，请重试！', {icon: 2});
					}
				},
				error : function() {
					layer.msg('操作失败，请重试！', {icon: 2});
				},
			});
		   // layer.msg('的确很重要', {icon: 1});
		}, function(){
		    
		});
		
	}
</script>

<body>
	<div id="content" style="height: 950px;">
		<div style="color: #025D7B; height: 26px; line-height: 26px;">
			<span>优惠券定义</span> <span>&gt;</span> <span>优惠券修改</span>
		</div>
		<div class="hr"></div>
		<form:form id="couponForm" action="" class="form-horizontal"
			method="post" modelAttribute="dto" role="form">
			<input type="text" class="hidden" id="ticketDefId" name="ticketDefId"
				value="${ticket.id}" />
			<input type="text" class="hidden" id="qticketType" name="qticketType"
				value="${qticketType}" />
			<input type="text" class="hidden" id="qticketName" name="qticketName"
				value="${qticketName}" />

			<input type="text" class="hidden" id="ticketType" name="ticketType"
				value="${ticket.ticketType}" />

			<input type="text" class="hidden" id="pager" name="pager.currentPage"
				value="${currentPage}">

			<div class="row rowDiv">
				<div class="form-group formDiv">
					<label class="col-sm-3 control-label" for="ticketName">名称</label>
					<div class="col-sm-6">
						<input class="form-control input-sm" id="ticketName"
							name="ticketName" type="text" value="${ticket.ticketName}"
							check-type="required" required-message="请填写名称" />
					</div>
				</div>
				<div class="form-group formDiv">
					<label class="col-sm-3 control-label" for="maximunTimes">最大使用次数 </label>
					<div class="col-sm-6">
						<input class="form-control input-sm" id="maximunTimes"
							name="maximunTimes" type="text" value="${ticket.maximunTimes}"
							check-type="required" required-message="最大使用次数" />
					</div>
				</div>
			</div>
			<div class="row rowDiv">
				<div class="form-group formDiv">
					<label class="col-sm-3 control-label" for="deductionMethod">抵扣方式</label>
					<div class="col-sm-6">
						<select id="deductionMethod" name="deductionMethod"
							value="${ticket.deductionMethod}" class="form-control input-sm">
							<option value="AMOUNT">金额</option>
							<option value="PERCENT">百分比</option>
						</select>
					</div>
				</div>
				<div class="form-group formDiv">
					<label class="col-sm-3 control-label" for="deductionAmount">抵扣值</label>
					<div class="col-sm-7">
						<input class="form-control input-sm text-right"
							id="deductionAmount" value="${ticket.deductionAmount}"
							name="deductionAmount" type="text" check-type="required"
							required-message="请填写抵扣值" />
					</div>
				</div>
			</div>
			<div class="row rowDiv">
				<div class="form-group formDiv">
					<label class="col-sm-3 control-label" for="verificationMethod">抵扣凭证</label>
					<div class="col-sm-3">
						<select id="verificationMethod" name="verificationMethod"
							value="${ticket.verificationMethod}"
							class="form-control input-sm">
							<option value="CODE">抵扣码</option>
							<option value="N/A">无</option>
						</select>
					</div>
				</div>
				<div class="form-group formDiv">
					<label class="col-sm-3 control-label" for="smsRemind">是否发送使用短信</label>
					<label class="radio-inline"> <input type="radio"
						name="smsRemind" id="smsRemind1" value="1">是
					</label> <label class="radio-inline"> <input type="radio"
						name="smsRemind" id="smsRemind2" value="0">否
					</label>
				</div>
			</div>
		</form:form>
		<div style="margin-left: 300px;">
			<button type="button" class="btn btn-success btn-sm" id="saveBtn">
				<i class="glyphicon glyphicon-floppy-saved" style="color: #FFFFFF"></i>&nbsp;保
				存
			</button>
			<button type="button" class="btn btn-success btn-sm"
				onclick="insertRow()">
				<i class="glyphicon glyphicon-plus" style="color: #FFFFFF"></i>&nbsp;添加产品
			</button>
			<button type="button" class="btn btn-success btn-sm" id="returnBtn">
				<i class="glyphicon glyphicon-retweet" style="color: #FFFFFF"></i>&nbsp;返回
			</button>
		</div>
		<form:form id="search_form" action="" class="form-horizontal"
			method="post" modelAttribute="dto" role="form">
			<table id="data_tabs" class="table"
				style="margin-top: 20px; margin-left: 20px; width: 60%;">
				<thead>
					<tr>
						<th width="20%">产品编号</th>
						<th width="20%">产品说明</th>
						<th width="5%">数量</th>
						<th width="30%">操作</th>
					</tr>
				</thead>
				<tbody>
					<core:forEach items="${ticketLineList}" var="list">
						<tr>
							<td>${list.id}</td>
							<td>${list.itemName}</td>
							<td class="text-right">${list.quantity}</td>
							<td class="text-left">
								<button type="button" class="btn btn-success btn-xs btnLength"
									onClick="editCouponLineInfo('${list.id}')">修改</button>
								<button type="button" class="btn btn-success btn-xs btnLength" onClick="toScopeOfTicket('${list.id}')">适用范围</button>
								<button type="button" class="btn btn-success btn-xs btnLength"
									onClick="removeCouponLine('${list.id}')">删除</button>
							</td>
						</tr>
					</core:forEach>
				</tbody>
			</table>
		</form:form>
		
		<hr/>
		<fieldset>
		<legend>优惠券适用范围定义 <button type="button" class="btn btn-success btn-sm"
				onclick="addEligibility()">
				<i class="glyphicon glyphicon-plus" style="color: #FFFFFF"></i>&nbsp;添加
			</button></legend>
		<table id="data_tabs2" class="table"
				style="margin-top: 0px; margin-left: 20px; width: 60%;">
				<thead>
					<tr>
						<th width="20%">门店属性</th>
						<th width="50%">属性值</th>
						<th width="30%">操作</th>
					</tr>
				</thead>
				<tbody>
					<core:forEach items="${couponEligibilityList}" var="eligibility">
						<tr>
							<td>${eligibility.dealerProperty}</td>
							<td class="text-left">${eligibility.propertyValue}</td>
							<td class="text-left">
								<button type="button" class="btn btn-success btn-xs btnLength"
									onClick="editEligibility('${eligibility.id}')">修改</button>
								<button type="button" class="btn btn-success btn-xs btnLength"
									onClick="removeEligibility('${eligibility.id}')">删除</button>
							</td>
						</tr>
					</core:forEach>
				</tbody>
			</table>
		</fieldset>
		
		
	</div>
	
<script type="text/javascript">

ns = {

	    ok: function (msg, fn) {

	        return layer.msg(msg, {icon: 1, time: 1500,offset: ['100px', '350px'], shade: [0.1, '#000']}, fn);

	    },



	    error: function (msg) {

	        return layer.alert(msg, {icon: 5, offset: ['100px', '250px'] });

	        //return layer.msg(msg, {icon: 5, time: 3000, shade: [0.2, '#000']});

	    },

	    errorTip: function (msg) {

	        return layer.msg(msg, {icon: 5, time: 3000, shade: [0.1, '#000']});

	    },





	    load: function (msg, fn) {

	        if(!msg){

	            return layer.load(1, {shade: [0.1, '#000']});

	        }



	        return layer.msg(msg, {

	            icon: 16,

	            shade: [0.1, '#000'],

	            time: 0//2秒关闭（如果不配置，默认是3秒）

	        }, fn);

	    }



	    ,close : function(index){

	        layer.close(index);

	    }



	    ,closeAll : function(){

	        layer.closeAll();

	    }





	};



function addEligibility(){
	var contentHtml = $("#couponEligibilityTemplate").html();
    openEditWin("新增", contentHtml);

}



function editEligibility(id) {

	
	var contentHtml = $("#couponEligibilityTemplate").html();
    //Ajax获取

    var loadIndex = ns.load();

    $.ajax({
        type: "POST",
        url : '${webcontext}/crmdp/dealer/coupon/eligibility/load/' + id,
        dataType: "json",
        success: function (data) {
            ns.close(loadIndex);
            if (data.success) {
                ns.close(loadIndex);
                openEditWin("编辑", contentHtml, data.data);
            } else {
                ns.error('提交失败' + data.message);
            }
        },
        error: function () {
            ns.close(loadIndex);
            ns.error('提交失败！');
        }
    });
}





function openEditWin(title, contentHtml, editData) {

    layer.open({
        type: 1,
        offset: ['100px', '250px'],
        title: title,
        area: '500px',
        btn: ['保 存', '取 消'],
        content: contentHtml,
        yes: function (index, layero) {
            var layerIndex = ns.load();
            $.ajax({
                type: "POST",
                url : '${webcontext}/crmdp/dealer/coupon/eligibility/save/',
                dataType: "json",
                data: $("#couponEligibilityForm").serialize(),
                success: function (data) {
                    ns.close(layerIndex);
                    if (data.success) {
                        ns.ok('操作成功!', function () {
                            ns.closeAll();
                            location.reload();
                        });
                    } else {
                        ns.error('提交失败' + data.message);
                    }
                },
                error: function () {
                    ns.close(layerIndex);
                    ns.error('提交失败！');
                }
            });
        }, cancel: function (index) {
            ns.closeAll();
        },success: function(layero, index){
            if(editData){
            	$("#couponEligibilityForm_propertyValue").val(editData.propertyValue);
            	$("#couponEligibilityForm_id").val(editData.id);
            	$("#couponEligibilityForm_ticketDefId").val(editData.ticketDefId);
            	$("#couponEligibilityForm_dealerProperty").val(editData.dealerProperty);
            }
        }
    });
}



</script>

<script type="text/html" id="couponEligibilityTemplate">
<form id="couponEligibilityForm" action="" class="form"	method="post" role="form">
	<input type="text" class="hidden" id="couponEligibilityForm_id" name="id"	value="" />
	<input type="text" class="hidden" id="couponEligibilityForm_ticketDefId" name="ticketDefId" value="${ticket.id}" />

<div style="margin:10px 30px;">
		<div class="form-group">
			<label class="control-label" for="ticketName">门店属性</label>
			<select id="couponEligibilityForm_dealerProperty" class='form-control input-sm' name="dealerProperty" style='width: 320px;'>
				<option value=''>--------请选择门店属性---------</option>
				<core:forEach items='${codeInfoList}' var='list'>
					<option value='${list.code}'>${list.value}</option>
				</core:forEach>
			</select>
		</div>

		<div class="form-group">
			<label class="control-label" for="propertyValue">属性值 </label>
				<input class="form-control input-sm" id="couponEligibilityForm_propertyValue"
					name="propertyValue" type="text" value=""
					check-type="required" />
		</div>
</div>
	
</form>
</script>
</body>
</html>